package io.sundial.console.datasource.dao;

import io.sundial.console.datasource.core.Datasource;
import io.sundial.console.datasource.core.DatasourceType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Date;

/**
 * 数据源仓储接口
 *
 * @author Payne 646742615@qq.com
 * 2019/1/3 16:16
 */
public interface DatasourceRepository extends JpaRepository<Datasource, String> {

    @Query("FROM Datasource AS ds WHERE ds.name LIKE :keyword OR ds.address LIKE :keyword OR ds.catalog LIKE :keyword OR ds.description LIKE :keyword")
    Page<Datasource> search(@Param("keyword") String keyword, Pageable pageable);

    @Modifying
    @Query("UPDATE Datasource AS ds SET ds.disabled = true, ds.version = ds.version + 1 WHERE ds.name = :name")
    void disable(@Param("name") String name);

    @Modifying
    @Query("UPDATE Datasource AS ds SET ds.disabled = false, ds.version = ds.version + 1 WHERE ds.name = :name")
    void enable(@Param("name") String name);

    @Modifying
    @Query("UPDATE Datasource AS ds SET ds.type = :type, ds.address = :address, ds.catalog = :catalog, ds.username = :username, ds.password = :password, ds.description = :description, ds.lastUpdated = :lastUpdated, ds.version = ds.version + 1 WHERE ds.name = :name")
    void update(
            @Param("name") String name,
            @Param("type") DatasourceType type,
            @Param("address") String address,
            @Param("catalog") String catalog,
            @Param("username") String username,
            @Param("password") String password,
            @Param("description") String description,
            @Param("lastUpdated") Date lastUpdated
    );

    @Modifying
    @Query("DELETE FROM Datasource WHERE name = :name")
    void delete(@Param("name") String name);

}
